package jsyf.oa.service.wreport;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import jsyf.oa.dao.system.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import jsyf.com.dao.BaseJdbcDao;
import jsyf.com.util.DateUtils;
import jsyf.com.util.FastJsonConvert;
import jsyf.oa.dao.wechat.service_company.TokenDao;
import jsyf.oa.dao.wreport.CostAuditDao;
import jsyf.oa.dao.wreport.CostCopierDao;
import jsyf.oa.dao.wreport.CostDetailDao;
import jsyf.oa.dao.wreport.WReportCostDao;
import jsyf.oa.dao.wreport.WReportMainDao;
import jsyf.oa.entity.system.AuditHistoryEntity;
import jsyf.oa.entity.system.UserEntity;
import jsyf.oa.entity.wreport.CostAuditEntity;
import jsyf.oa.entity.wreport.CostCopierEntity;
import jsyf.oa.entity.wreport.CostDetailEntity;
import jsyf.oa.entity.wreport.WReportCostAllEntity;
import jsyf.oa.entity.wreport.WReportCostEntity;
import jsyf.oa.entity.wreport.WReportMainEntity;
import jsyf.oa.facade.wreport.WReportCostFacade;

import static jsyf.oa.dao.wechat.service_company.TokenDao.MsgTemplate.COST_AUDIT_AUDIT;
import static jsyf.oa.dao.wechat.service_company.TokenDao.MsgTemplate.COST_AUDIT_CANCEL;
import static jsyf.oa.dao.wechat.service_company.TokenDao.MsgTemplate.COST_AUDIT_PASS;
import static jsyf.oa.dao.wechat.service_company.TokenDao.MsgTemplate.COST_AUDIT_PASSONE;
import static jsyf.oa.dao.wechat.service_company.TokenDao.MsgTemplate.COST_AUDIT_REJECT;
import static jsyf.oa.dao.wechat.service_company.TokenDao.MsgTemplate.COST_AUDIT_REJECTONE;
import static jsyf.oa.dao.wechat.service_company.TokenDao.MsgTemplate.COST_COPIER_REJECT;
import static jsyf.oa.dao.wechat.service_company.TokenDao.PushTemplate.COST_AUDIT_NOTIFY;


/**
 * Created by Administrator on 2017/12/29 0029.
 */
@Service
@Transactional(rollbackFor = Exception.class)
@com.alibaba.dubbo.config.annotation.Service(protocol = {"dubbo"})
public class WReportCostService implements WReportCostFacade {
    @Autowired
    private RightOpDao rightOpDao;
    @Autowired
    private User2RightOpDao user2RightOpDao;
    @Autowired
    private TokenDao tokenDao;
    @Autowired
    private WReportCostDao dao;
    @Autowired
    private CostDetailDao costDetailDao;
    @Autowired
    private CostAuditDao costAuditDao;
    @Autowired
    private CostCopierDao costCopierDao;
    @Autowired
    private UserDao userDao;
    @Autowired
    private WReportMainDao wReportMainDao;
    @Autowired
    private CompanyDao companyDao;
    @Autowired
    private DepartDao departDao;
    @Autowired
    private AuditHistoryDao auditHistoryDao;
    @Autowired
    private User2RegionDao user2RegionDao;
    @Autowired
    private CheckDao checkDao;

    private JSONObject object;
    private JSONObject auditor;
    private List<CostCopierEntity> copierEntityList;
    private List<CostAuditEntity> auditEntityList;

    @Override
    public boolean config(String costIds, Integer start) {
        if (!com.alibaba.dubbo.common.utils.StringUtils.isEmpty(costIds)) {
            List<String> list = BaseJdbcDao.stringToList(costIds);
            for (int i = 0; i < list.size(); i++) {
                WReportCostEntity entity = new WReportCostEntity();
                entity.setId(list.get(i));
                entity.setStart(start);
                dao.update(entity);
            }
        }
        return true;
    }

    @Override
    public List<JSONObject> getByUserIdAndReport(String userId, String reportDate) {
        StringBuffer sql = new StringBuffer();
        sql.append(" AND \n");
        sql.append(" T_SYS_USER.ID IN( SELECT USER_ID FROM T_SYS_USER_2_REGION \n");
        sql.append(" WHERE 1=1 AND REGION_ID in(SELECT REGION_ID FROM T_SYS_USER_2_REGION  \n");
        sql.append(" WHERE 1=1 AND  USER_ID=?)) \n");
        sql.append(" AND T_WRT_MAIN.REPORT_DATE LIKE ? \n");
        sql.append(" AND T_WRT_MAIN.FLAGE = 0 \n");
        sql.append(" AND T_WRT_COST.MONEY IS NOT NULL \n");
        return dao.getByUserIdAndReport(sql.toString(), new Object[]{userId, "%" + reportDate + "%"});
    }

    @Override
    public List<JSONObject> getByDepartIdAndReport(String departId, String reportDate) {
        StringBuffer sql = new StringBuffer();
        sql.append(" AND v_sys_user.departId= ? \n");
        sql.append(" AND T_WRT_MAIN.REPORT_DATE LIKE ? \n");
        sql.append(" AND T_WRT_MAIN.FLAGE = 0 \n");
        sql.append(" AND T_WRT_COST.MONEY IS NOT NULL \n");
        return dao.getByDepartIdAndReport(sql.toString(), new Object[]{departId, "%" + reportDate + "%"});
    }


    @Override
    public List<JSONObject> getByCondition(String userId, String beginTime, String endTime, String costIds, String type) {
        StringBuffer sbCondition = new StringBuffer();
        String costIdss = "";
        if (!StringUtils.isBlank(userId)) {
            sbCondition.append(" where 1=1  AND userId='" + userId + "'");
            sbCondition.append(" AND bxstate='0'");
        }
        if (!StringUtils.isBlank(type) && type.equals("1")) {
            sbCondition.append(" OR bxstate='1'");
        }

        if (!StringUtils.isBlank(beginTime) && !StringUtils.isBlank(endTime)) {
            sbCondition.append("\tAND\n");
            sbCondition.append("\tV_WRT_COST2.reportDate BETWEEN '" + beginTime + "' AND '" + endTime + "'\n");
        }
        if (!StringUtils.isBlank(beginTime) && StringUtils.isBlank(endTime)) {
            sbCondition.append("\tAND\n");
            sbCondition.append("\tV_WRT_COST2.reportDate >= '" + beginTime + "'\n");
        }
        if (!StringUtils.isBlank(endTime) && StringUtils.isBlank(beginTime)) {
            sbCondition.append("\tAND\n");
            sbCondition.append("\tV_WRT_COST2.reportDate <='" + endTime + "'\n");
        }
        if (costIds.length() > 0 || !StringUtils.isBlank(costIds)) {
            costIdss = "'" + costIds + "'";
            sbCondition.append("\tAND\n");
            sbCondition.append("\tV_WRT_COST2.id in(" + costIdss + ")\n");
        }
        sbCondition.append(" ORDER BY V_WRT_COST2.companyId,V_WRT_COST2.departId,V_WRT_COST2.userId");
        return dao.getViewByPage(sbCondition.toString(), new Object[]{}, 1, Integer.MAX_VALUE);

    }

    @Override
    public String save(String jsonData) {
        WReportCostAllEntity wReportCostAllEntity = JSON.toJavaObject(JSON.parseObject(jsonData), WReportCostAllEntity.class);
        //第一步，保存主表信息
        WReportCostEntity wReportCostEntity = wReportCostAllEntity.getMain();
        CostDetailEntity costDetailEntity = wReportCostAllEntity.getCost();
        Integer costSmallId = wReportCostEntity.getCostSmallId();
        JSONObject object = dao.getByDetail(costSmallId);
        String costSmallName = object.getString("costSmallName");
        String costBigName = object.getString("costBigName");
        String costBigId = object.getString("costBigId");
        wReportCostEntity.setCostBigId(Integer.parseInt(costBigId));
        wReportCostEntity.setCostBigName(costBigName);
        wReportCostEntity.setCostSmallName(costSmallName);
        wReportCostEntity.setCreateTime(dao.getCurrentTime());
        wReportCostEntity.setStart(0);
        wReportCostEntity.setCurrentAuditorId("");
        wReportCostEntity.setCurrentAuditorName("");

        //如果是提交申请
        if ("0".equals(wReportCostEntity.getAuditFlag())) {
            //设置第一审核人
            List<CostAuditEntity> auditorEntityList = wReportCostAllEntity.getAuditors();
            if (auditorEntityList != null && auditorEntityList.size() > 0) {
                CostAuditEntity firstAuditor = wReportCostAllEntity.getAuditors().get(0);
                wReportCostEntity.setCurrentAuditorId(firstAuditor.getAuditorId());
                String[] arrAuditorName = firstAuditor.getAuditorName().split("-");
                wReportCostEntity.setCurrentAuditorName(arrAuditorName[arrAuditorName.length - 1]);
            }
        }

        if (StringUtils.isBlank(wReportCostEntity.getId()) || "0".equals(wReportCostEntity.getId())) {
            //新建
            wReportCostEntity.setReportDate(new SimpleDateFormat("yyyy-MM-dd").format(dao.getCurrentTime()));
            dao.add(wReportCostEntity);
        } else {
            WReportCostEntity oldEntity = dao.getEntityById(wReportCostEntity.getId());
            oldEntity.setwId(wReportCostEntity.getwId());
            oldEntity.setCostBigId(wReportCostEntity.getCostBigId());
            oldEntity.setCostBigName(wReportCostEntity.getCostBigName());
            oldEntity.setCostSmallId(wReportCostEntity.getCostSmallId());
            oldEntity.setCostSmallName(wReportCostEntity.getCostSmallName());
            oldEntity.setMoney(wReportCostEntity.getMoney());
            oldEntity.setInvoiceFlag(wReportCostEntity.getInvoiceFlag());
            oldEntity.setRemark(wReportCostEntity.getRemark());
            oldEntity.setStart(wReportCostEntity.getStart());
            oldEntity.setAuditFlag(wReportCostEntity.getAuditFlag());
            oldEntity.setReportDate(wReportCostEntity.getReportDate());
            oldEntity.setCreateUserId(wReportCostEntity.getCreateUserId());
            oldEntity.setCreateUserName(wReportCostEntity.getCreateUserName());
            oldEntity.setCurrentAuditorId(wReportCostEntity.getCurrentAuditorId());
            oldEntity.setCurrentAuditorName(wReportCostEntity.getCurrentAuditorName());
            dao.update(oldEntity);
        }
        String mainId = wReportCostEntity.getId();
        if ("0".equals(wReportCostEntity.getAuditFlag())) {
            List<CostAuditEntity> auditorEntityList = wReportCostAllEntity.getAuditors();
            if (auditorEntityList != null && auditorEntityList.size() > 0) {
                CostAuditEntity firstAuditor = wReportCostAllEntity.getAuditors().get(0);
                //企业号:给第一审核人发送消息
                JSONObject msgObject = new JSONObject();
                msgObject.put("userIds", firstAuditor.getAuditorId());
                msgObject.put("content", String.format(COST_AUDIT_AUDIT,
                        firstAuditor.getAuditorName(),
                        wReportCostEntity.getCostSmallName(),
                        wReportCostEntity.getRemark(),
                        wReportCostEntity.getCreateUserName(),
                        DateUtils.parse(wReportCostEntity.getCreateTime(), "yyyy-MM-dd HH:mm"),
                        wReportCostEntity.getId(),
                        wReportCostEntity.getCurrentAuditorId()
                ));
                tokenDao.sendTextMsg(JSON.toJSONString(msgObject));
                //推送: 给第一审核人推送红点提示
                tokenDao.sendJPushMsg(firstAuditor.getAuditorId(), String.format(COST_AUDIT_NOTIFY, wReportCostEntity.getCreateUserName()));
            }
        }

        costDetailEntity.setFkCostId(mainId);


        //费用详情表
        if (StringUtils.isBlank(costDetailEntity.getId()) || "0".equals(costDetailEntity.getId())) {
            //新建
            costDetailDao.add(costDetailEntity);
        } else {
            CostDetailEntity oldDetailEntity = costDetailDao.getEntityById(costDetailEntity.getId());
            oldDetailEntity.setLicense(costDetailEntity.getLicense());
            oldDetailEntity.setPredictMoney(costDetailEntity.getPredictMoney());
            oldDetailEntity.setMileage(costDetailEntity.getMileage());
            oldDetailEntity.setFkCostId(costDetailEntity.getFkCostId());
            oldDetailEntity.setGuestNature(costDetailEntity.getGuestNature());
            oldDetailEntity.setGuests(costDetailEntity.getGuests());
            oldDetailEntity.setHost(costDetailEntity.getHost());
            oldDetailEntity.setImg(costDetailEntity.getImg());
            oldDetailEntity.setHotelName(costDetailEntity.getHotelName());
            oldDetailEntity.setHotelTel(costDetailEntity.getHotelTel());
            oldDetailEntity.setResidence(costDetailEntity.getResidence());
            oldDetailEntity.setCohabitation(costDetailEntity.getCohabitation());
            oldDetailEntity.setRestaurantName(costDetailEntity.getRestaurantName());
            oldDetailEntity.setRestaurantTel(costDetailEntity.getRestaurantTel());
            oldDetailEntity.setEntertainmentVenue(costDetailEntity.getEntertainmentVenue());
            oldDetailEntity.setPhone(costDetailEntity.getPhone());
            oldDetailEntity.setBeforeOffice(costDetailEntity.getBeforeOffice());
            oldDetailEntity.setAfterOffice(costDetailEntity.getAfterOffice());
            oldDetailEntity.setOfficeMatters(costDetailEntity.getOfficeMatters());
            costDetailDao.update(oldDetailEntity);
        }

        //第二步，保存抄送人信息
        // 删除
        costCopierDao.removeByCondition(" AND FK_COST_ID = ?", new String[]{mainId});
        List<CostCopierEntity> copierEntityList = wReportCostAllEntity.getCopiers();
        if (copierEntityList != null && copierEntityList.size() > 0) {
            for (int i = 0; i < copierEntityList.size(); i++) {
                copierEntityList.get(i).setFkCostId(mainId);
                this.costCopierDao.add(copierEntityList.get(i));
            }
        } else {
            //如果没写抄送人默认添加(区域支持)和上级为抄送人
            JSONObject Copier = userDao.getSupportByUserId(wReportCostEntity.getCreateUserId());
            UserEntity firstCopier = JSON.toJavaObject(Copier, UserEntity.class);
            if (firstCopier != null) {
                CostCopierEntity copier = new CostCopierEntity();
                copier.setFkCostId(mainId);
                copier.setCopyPersonId(firstCopier.getId());
                copier.setCopyPersonName(firstCopier.getName());
                costCopierDao.add(copier);
            }
            List<JSONObject> secondCopiers = getParentList(wReportCostEntity.getCreateUserId());
            if (secondCopiers != null && secondCopiers.size() > 0) {
                for (JSONObject JSONObject : secondCopiers) {
                    if (!"".equals(JSONObject.getString("id"))) {

                        UserEntity copierEntity = JSON.toJavaObject(JSONObject, UserEntity.class);
                        CostCopierEntity copier = new CostCopierEntity();
                        copier.setFkCostId(mainId);
                        copier.setCopyPersonId(copierEntity.getId());
                        copier.setCopyPersonName(copierEntity.getName());
                        costCopierDao.add(copier);
                    }

                }
            }

        }
        //第三步，保存审核人信息
        //删除
        costAuditDao.removeByCondition(" AND FK_COST_ID = ?", new String[]{mainId});
        //添加
        List<CostAuditEntity> auditEntityList = wReportCostAllEntity.getAuditors();
        if (auditEntityList != null && auditEntityList.size() > 0) {
            for (int i = 0; i < auditEntityList.size(); i++) {
                WReportCostEntity oldEntity = dao.getEntityById(wReportCostEntity.getId());
                if (!StringUtils.isBlank(oldEntity.getCopierReturnReason())) {
                    oldEntity.setCopierReturnReason("");
                    dao.update(oldEntity);
                    auditEntityList.get(i).setAuditFlag("0");
                    auditEntityList.get(i).setAuditAdvise("");
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    java.util.Date uDate = null;
                    try {
                        uDate = sdf.parse("");
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    auditEntityList.get(i).setAuditTime(uDate);
                } else if (!StringUtils.isBlank(auditEntityList.get(i).getAuditAdvise()) && "2".equals(auditEntityList.get(i).getAuditFlag())) {
                    auditEntityList.get(i).setAuditFlag("0");
                    auditEntityList.get(i).setAuditAdvise("");
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    java.util.Date uDate = null;
                    try {
                        uDate = sdf.parse("");
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    auditEntityList.get(i).setAuditTime(uDate);
                }
                auditEntityList.get(i).setFkCostId(mainId);

                this.costAuditDao.add(auditEntityList.get(i));
            }
        } else {
            //如果没写审核人默认添加上级为审核人
            JSONObject Auditor = userDao.getFirstParent(wReportCostEntity.getCreateUserId());
            CostAuditEntity audit = new CostAuditEntity();
            UserEntity firstAuditor = JSON.toJavaObject(Auditor, UserEntity.class);
            if (firstAuditor != null) {
                audit.setFkCostId(mainId);
                audit.setAuditFlag("0");
                audit.setAuditTime(null);
                audit.setAuditAdvise("");
                audit.setAuditorId(firstAuditor.getId());
                audit.setAuditorName(firstAuditor.getName());
                costAuditDao.add(audit);
            }

        }
        return mainId;
    }

    public List<JSONObject> getParentList(String userId) {
        List<JSONObject> parentList = new ArrayList<>();
        List<JSONObject> jsonParent = this.userDao.getParentList(userId, parentList);
        //判断上级
        JSONObject fistParent = this.userDao.getFirstParent(userId);
        for (int i = 0; i < jsonParent.size(); i++) {
            if (fistParent.getString("id").equals(jsonParent.get(i).getString("id"))) {
                jsonParent.remove(i);
                break;
            }
        }
        return jsonParent;
    }

    @Override
    public Boolean applyAudit(String id, String userId, String auditFlag, String advise) {
        //保存历史审核信息
        AuditHistoryEntity auditHistoryEntity = new AuditHistoryEntity();
        auditHistoryEntity.setMainId(id);
        auditHistoryEntity.setAuditorId(userId);
        JSONObject user = userDao.getJSONById(userId);
        auditHistoryEntity.setAuditorName(user.getString("name"));
        auditHistoryEntity.setAuditFlag(auditFlag);
        auditHistoryEntity.setAuditAdvise(advise);
        auditHistoryEntity.setAuditType(3);
        auditHistoryEntity.setAuditTime(costAuditDao.getCurrentTime());
        auditHistoryDao.add(auditHistoryEntity);
        //根据id获取主表信息
        WReportCostEntity wReportCostEntity = dao.getEntityById(id);
        //根据id获取审核信息
        List<CostAuditEntity> AuditEntityList = costAuditDao.getEntityListByCondition(" AND FK_COST_ID = ? ORDER BY AUDIT_SORT ", new Object[]{id});
        CostAuditEntity auditEntityNow = null;
        for (int i = 0; i < AuditEntityList.size(); i++) {
            //如果审核人==当前审核人
            if (AuditEntityList.get(i).getAuditorId().equals(userId)) {
                auditEntityNow = AuditEntityList.get(i);
                auditEntityNow.setAuditFlag(auditFlag);
                auditEntityNow.setAuditTime(costAuditDao.getCurrentTime());
                auditEntityNow.setAuditAdvise(advise);
                costAuditDao.update(auditEntityNow);

                //企业号:发消息通知申请人  (不发送给抄送人)
                JSONObject msgObject = new JSONObject();
                msgObject.put("userIds", wReportCostEntity.getCreateUserId());
                if ("2".equals(auditFlag)) {
                    //驳回
                    msgObject.put("content", String.format(COST_AUDIT_REJECT,
                            wReportCostEntity.getCreateUserName(),
                            wReportCostEntity.getCostSmallName(),
                            auditEntityNow.getAuditAdvise(),
                            auditEntityNow.getAuditorName(),
                            DateUtils.parse(auditEntityNow.getAuditTime(), "yyyy-MM-dd HH:mm")));
                    tokenDao.sendTextMsg(JSON.toJSONString(msgObject));

                    //企业号：审核驳回，发送消息给当前审核人
//                    JSONObject msgAuditObject = new JSONObject();
//                    msgAuditObject.put("userIds", auditEntityNow.getAuditorId());
//                    msgAuditObject.put("content", String.format(COST_AUDIT_REJECTONE,
//                            auditEntityNow.getAuditorName(),
//                            wReportCostEntity.getCostSmallName(),
//                            wReportCostEntity.getRemark(),
//                            wReportCostEntity.getCreateUserName(),
//                            DateUtils.parse(wReportCostEntity.getCreateTime(), "yyyy-MM-dd HH:mm"),
//                            wReportCostEntity.getId(),
//                            wReportCostEntity.getCurrentAuditorId()));
//                    tokenDao.sendTextMsg(JSON.toJSONString(msgAuditObject));

                }
                if ("1".equals(auditFlag)) {

                    //企业号：审核通过，发送消息给当前审核人
//                    JSONObject msgAuditObject = new JSONObject();
//                    msgAuditObject.put("userIds", auditEntityNow.getAuditorId());
//                    msgAuditObject.put("content", String.format(COST_AUDIT_PASSONE,
//                            auditEntityNow.getAuditorName(),
//                            wReportCostEntity.getCostSmallName(),
//                            wReportCostEntity.getRemark(),
//                            wReportCostEntity.getCreateUserName(),
//                            DateUtils.parse(wReportCostEntity.getCreateTime(), "yyyy-MM-dd HH:mm"),
//                            wReportCostEntity.getId(),
//                            wReportCostEntity.getCurrentAuditorId()));
//                    tokenDao.sendTextMsg(JSON.toJSONString(msgAuditObject));

                    if (i == AuditEntityList.size() - 1) {
                        wReportCostEntity.setAuditFlag(auditFlag);
                        wReportCostEntity.setCurrentAuditorId("");
                        wReportCostEntity.setCurrentAuditorName("");
                        WReportMainEntity main = wReportMainDao.getByUserIdAndReportDate(wReportCostEntity.getCreateUserId(), wReportCostEntity.getReportDate());
                        if (main != null) {
                            if (!StringUtils.isBlank(main.getId())) {
                                wReportCostEntity.setwId(main.getId());
                            }
                        }
                        dao.update(wReportCostEntity);
                        //企业号: 最后一个审核通过,发送消息给申请人
                        msgObject.put("userIds", wReportCostEntity.getCreateUserId());
                        msgObject.put("content", String.format(COST_AUDIT_PASS,
                                wReportCostEntity.getCreateUserName(),
                                wReportCostEntity.getCostSmallName(),
                                auditEntityNow.getAuditorName(),
                                DateUtils.parse(auditEntityNow.getAuditTime(), "yyyy-MM-dd HH:mm")));
                        tokenDao.sendTextMsg(JSON.toJSONString(msgObject));
                        //推送: 给申请人推送红点提示
//                        tokenDao.sendJPushMsg(wReportCostEntity.getCreateUserId(), String.format(COST_APPLY_NOTIFY, wReportCostEntity.getCreateUserName()));
                    } else {
                        CostAuditEntity auditEntityNext = AuditEntityList.get(i + 1);
                        auditEntityNext.setAuditFlag("0");
                        costAuditDao.update(auditEntityNext);
                        wReportCostEntity.setCurrentAuditorId(auditEntityNext.getAuditorId());
                        String[] arrAuditorName = auditEntityNext.getAuditorName().split("-");
                        wReportCostEntity.setCurrentAuditorName(arrAuditorName[arrAuditorName.length - 1]);
                        dao.update(wReportCostEntity);

                        //企业号: 审核通过,发送消息给申请人
                        msgObject.put("userIds", wReportCostEntity.getCreateUserId());
                        msgObject.put("content", String.format(COST_AUDIT_PASS,
                                wReportCostEntity.getCreateUserName(),
                                wReportCostEntity.getCostSmallName(),
                                auditEntityNow.getAuditorName(),
                                DateUtils.parse(auditEntityNow.getAuditTime(), "yyyy-MM-dd HH:mm")));
                        tokenDao.sendTextMsg(JSON.toJSONString(msgObject));

                        //企业号: 给下一审核人发消息
                        JSONObject msgNextObject = new JSONObject();
                        msgNextObject.put("userIds", auditEntityNext.getAuditorId());
                        msgNextObject.put("content", String.format(COST_AUDIT_AUDIT,
                                auditEntityNext.getAuditorName(),
                                wReportCostEntity.getCostSmallName(),
                                wReportCostEntity.getRemark(),
                                wReportCostEntity.getCreateUserName(),
                                DateUtils.parse(wReportCostEntity.getCreateTime(), "yyyy-MM-dd HH:mm"),
                                wReportCostEntity.getId(),
                                wReportCostEntity.getCurrentAuditorId()
                        ));
                        tokenDao.sendTextMsg(JSON.toJSONString(msgNextObject));
                        //推送: 给下一审核人推送红点提示
                        tokenDao.sendJPushMsg(auditEntityNext.getAuditorId(), String.format(COST_AUDIT_NOTIFY, wReportCostEntity.getCreateUserName()));
                    }
                } else {
                    wReportCostEntity.setAuditFlag(auditFlag);
                    wReportCostEntity.setCurrentAuditorId("");
                    wReportCostEntity.setCurrentAuditorName("");
                    dao.update(wReportCostEntity);
                }
                break;
            }
        }
        return true;
    }

    @Override
    public Boolean removeById(String id) {
        WReportCostEntity oldEntity = dao.getEntityById(id);
        costAuditDao.removeByCondition(" AND FK_COST_ID = ?", new String[]{id});
        costCopierDao.removeByCondition(" AND FK_COST_ID = ?", new String[]{id});
        costDetailDao.removeByCondition(" AND FK_COST_ID = ?", new String[]{id});
        JSONObject msgObject = new JSONObject();
        msgObject.put("userIds", oldEntity.getCurrentAuditorId());
        msgObject.put("content", String.format(COST_AUDIT_CANCEL,
                oldEntity.getCurrentAuditorName(),
                oldEntity.getCostSmallName(),
                oldEntity.getRemark(),
                oldEntity.getCreateUserName(),
                DateUtils.parse(oldEntity.getCreateTime(), "yyyy-MM-dd HH:mm")));
        tokenDao.sendTextMsg(JSON.toJSONString(msgObject));
        return dao.removeById(id) > 0;
    }

    @Override
    public String getUnDoCount(String userId) {
        Integer count = 0;
        if (userId != null && !userId.isEmpty()) {
            count = dao.getUnDoCount(userId);
        }
        return count.toString();
    }

    @Override
    public JSONObject getById(String id) {
        JSONObject object = new JSONObject();
        //WReportCostAllEntity wReportCostAllEntity=new WReportCostAllEntity();
        List<JSONObject> IBaseEntitys = this.costDetailDao.getJSONListByCondition(" AND FK_COST_ID = ? ", new String[]{id});
        for (JSONObject entity : IBaseEntitys) {
            object.put("cost", entity);
        }
        object.put("main", this.dao.getJSONById(id));
        object.put("copiers", this.costCopierDao.getJSONListByCondition(" AND FK_COST_ID = ? ", new Object[]{id}));
        object.put("auditors", this.costAuditDao.getJSONListByCondition(" AND FK_COST_ID = ? ", new Object[]{id}));
        object.put("historys", this.auditHistoryDao.getEntityListByCondition(" AND MAIN_ID =? AND AUDIT_FLAG=2 ORDER BY AUDIT_TIME DESC", new Object[]{id}));
        //wReportCostAllEntity.setMain(this.dao.getEntityById(id));
        //wReportCostAllEntity.setCopiers(this.costCopierDao.getEntityListByCondition(" AND FK_COST_ID = ? ", new Object[]{id}));
        //wReportCostAllEntity.setAuditors(this.costAuditDao.getEntityListByCondition(" AND FK_COST_ID = ? ORDER BY AUDIT_SORT ", new Object[]{id}));
        //return (JSONObject) JSON.toJSON(wReportCostAllEntity);
        return object;
    }


    @Override
    public Boolean copierReturn(String id, String copierReturnReason) {
        boolean success = dao.copierReturn(id, copierReturnReason) > 0;
        if (success) {
            //企业号 抄送人驳回
            WReportCostEntity oldEntity = dao.getEntityById(id);
            JSONObject msgObject = new JSONObject();
            msgObject.put("userIds", oldEntity.getCreateUserId());
            msgObject.put("content", String.format(COST_COPIER_REJECT,
                    oldEntity.getCreateUserName(),
                    oldEntity.getCostSmallName(),
                    oldEntity.getCopierReturnReason()));
            tokenDao.sendTextMsg(JSON.toJSONString(msgObject));
        }
        return success;
    }

    @Override
    public List<JSONObject> getCosterTop10ByCostName(String jsonData) {
        JSONObject JSONObject = JSON.parseObject(jsonData);
        String costName = JSONObject.getString("key");
        String condition = "";
        if (!StringUtils.isBlank(costName)) {
            condition = " and name LIKE ? ";
        }
        return dao.getCosterTop10ByCostName(condition, new Object[]{"%" + costName + "%"});

    }

    @Override
    public JSONObject getByPage(String userId, String key, String auditFlag, String costSmallName, String createUserName, int requestPage, int pageSize) {
        StringBuilder condition = new StringBuilder();
        List<Object> sqlArgs = new ArrayList<Object>();
        condition.append(" LEFT JOIN T_WRT_COST_DETAIL ON T_WRT_COST.ID = T_WRT_COST_DETAIL.FK_COST_ID");
        condition.append(" WHERE 1=1");
        condition.append(" AND AUDIT_FLAG IS NOT NULL ");
        if (StringUtils.isNotEmpty(key)) {
            condition.append(" AND (REMARK LIKE '%" + key + "%'OR CREATE_USER_NAME LIKE '%" + key + "%') ");
        }
        if (StringUtils.isNotEmpty(auditFlag)) {
            condition.append(" AND AUDIT_FLAG = ?");
            sqlArgs.add(auditFlag);
        }
        if (StringUtils.isNotEmpty(costSmallName)) {
            if (!costSmallName.equals("费用名称")) {
                condition.append(" AND COST_SMALL_NAME = ? ");
                sqlArgs.add(costSmallName);
            }
        }
        if (StringUtils.isNotEmpty(createUserName)) {
            condition.append(" AND CREATE_USER_NAME LIKE  '%" + createUserName + "%'");
        }
        condition.append(" AND (CREATE_USER_ID = ? ");
        condition.append("  OR ( ");
        condition.append("  AUDIT_FLAG <> '-1' ");
        condition.append("  AND ( ");
        condition.append(" T_WRT_COST.ID IN(SELECT FK_COST_ID FROM t_wrt_cost_audit WHERE AUDITOR_ID = ? AND AUDIT_FLAG <> '-1') ");
        condition.append(" OR ");
        condition.append(" T_WRT_COST.ID IN(SELECT FK_COST_ID FROM t_wrt_cost_copier WHERE COPY_PERSON_ID = ?) ");
        condition.append(" ) ");
        condition.append(" ) ");
        condition.append(" ) ");

        sqlArgs.add(userId);
        sqlArgs.add(userId);
        sqlArgs.add(userId);
        List<JSONObject> prerecords = this.dao.getJSONListByPage1(userId, condition.toString(), sqlArgs.toArray(), requestPage, pageSize);
        List<JSONObject> records = new ArrayList<JSONObject>();

        for (JSONObject o : prerecords) {
            String money = o.getString("money");
            String predictMoney = o.getString("predictMoney");
            if ("".equals(money) || StringUtils.isBlank(money)) {
                o.put("money", predictMoney);
            }
            if ("1".equals(o.getString("auditFlag")) && StringUtils.isBlank(o.getString("money")) || "".equals(o.getString("img"))) {
                o.put("flag", "1");
            } else {
                o.put("flag", "0");
            }
            records.add(o);
        }
        int recordCount = this.dao.getPageCount(condition.toString(), sqlArgs.toArray());
        int pageCount = 0;

        if (recordCount < pageSize) {
            pageCount = 1;
        } else {
            pageCount = (int) Math.ceil(recordCount / pageSize);
        }
        if (recordCount == 0) {
            pageCount = 0;
        }
        JSONObject objPager = new JSONObject();
        objPager.put("recordCount", recordCount);
        objPager.put("pageCount", pageCount);

        //返回
        JSONObject objResult = new JSONObject();
        objResult.put("records", records);
        objResult.put("pager", objPager);
        return objResult;
    }

    @Override
    public JSONObject getBxByPage(String jsonData) {
        JSONObject jsonParam = FastJsonConvert.convertJSONToObject(jsonData, JSONObject.class);
        String currentUserId = jsonParam.getString("currentUserId");
        String userId = jsonParam.getString("userId");
        String userName = jsonParam.getString("userName");
        String beginTime = jsonParam.getString("beginTime");
        String endTime = jsonParam.getString("endTime");
        String costSmallName = jsonParam.getString("costSmallName");
        String companyId = jsonParam.getString("companyId");
        String costSmallId = jsonParam.getString("costSmallId");

        String requestPage;
        String pageSize;
        if (jsonParam.containsKey("requestPage") && jsonParam.containsKey("pageSize")) {
            requestPage = jsonParam.getString("requestPage");
            pageSize = jsonParam.getString("pageSize");
        } else {
            requestPage = "1";
            pageSize = Integer.MAX_VALUE + "";
        }
        String companyIds = "";
        Boolean isMoneyRole = false;

        StringBuffer sbCondition = new StringBuffer();
        List<JSONObject> userList = userDao.getViewJSONListByCondition(" AND id=? ", new Object[]{currentUserId});
        String roleName = "";
        if (null != userList && userList.size() > 0) {
            for (int i = 0; i < userList.size(); i++) {
                roleName += userList.get(i).getString("roleName") + ",";
            }
        }
        //财务看公司所有的
        if (roleName.indexOf("财务") !=-1||roleName.indexOf("后台管理") !=-1) {
            isMoneyRole = true;
            //获取userId的所有公司
            if (null != userList && userList.size() > 0) {
                for (int i = 0; i < userList.size(); i++) {
                    String selectCompanyId = userList.get(i).getString("companyId");
                    String ids = companyDao.getChilderCompanyByCompanyId(selectCompanyId).getString("companyIds");
                    //如果有下级
                    if (!com.alibaba.dubbo.common.utils.StringUtils.isBlank(ids)) {
                        //如果有多个下级
                        if (ids.indexOf(",") >= 0) {
                            String[] idsSplit = ids.split(",");
                            for (String id : idsSplit) {
                                companyIds += "'" + id + "',";
                            }
                        } else {
                            //如果只有一个下级
                            companyIds += "'" + ids + "',";
                        }
                    }
                    companyIds += "'" + selectCompanyId + "',";
                }
                companyIds = companyIds.substring(0, companyIds.length() - 1);
            } else {
                companyIds = "''";
            }
        }
        String resignationUserIds = checkDao.getResignationByUserIdForCompany(currentUserId, true);
        String userIds = checkDao.getChilderByUserId(currentUserId, true);

        sbCondition.append(" where 1 =1 \n ");
        if (isMoneyRole) {
            sbCondition.append(" AND companyId in (" + companyIds + ")\n");
        }else{
            sbCondition.append(" AND (userId in(" + userIds + ") OR userId in(" + resignationUserIds + "))\n");
        }

        if (StringUtils.isBlank(userName)) {
            if (!StringUtils.isBlank(userId) && !isMoneyRole) {
                sbCondition.append(" AND userId='" + userId + "'");
            }
        } else {
            sbCondition.append(" AND userId='" + userId + "'");
        }

        if (!StringUtils.isBlank(companyId)) {
            sbCondition.append(" AND companyId='" + companyId + "'");
        }
        if (!StringUtils.isBlank(costSmallId)) {
            sbCondition.append(" AND costSmallId='" + costSmallId + "'");
        }

        if (!StringUtils.isBlank(beginTime) && !com.alibaba.dubbo.common.utils.StringUtils.isBlank(endTime)) {
            sbCondition.append("\tAND\n");
            sbCondition.append("\tV_WRT_COST2.reportDate BETWEEN '" + beginTime + "' AND '" + endTime + "'\n");
        }
        if (!StringUtils.isBlank(beginTime) && com.alibaba.dubbo.common.utils.StringUtils.isBlank(endTime)) {
            sbCondition.append("\tAND\n");
            sbCondition.append("\tV_WRT_COST2.reportDate = '" + beginTime + "'\n");
        }
        if (!StringUtils.isBlank(endTime) && com.alibaba.dubbo.common.utils.StringUtils.isBlank(beginTime)) {
            sbCondition.append("\tAND\n");
            sbCondition.append("\tV_WRT_COST2.reportDate = '" + endTime + "'\n");
        }
        if (!StringUtils.isBlank(costSmallName)) {
            sbCondition.append("\tAND\n");
            sbCondition.append("\tV_WRT_COST2.costSmallName = '" + costSmallName + "'\n");
        }
        sbCondition.append(" ORDER BY V_WRT_COST2.companyId,V_WRT_COST2.departId,V_WRT_COST2.userId,V_WRT_COST2.reportDate desc");
        List<JSONObject> records = dao.getViewByPage(sbCondition.toString(), new Object[]{}, Integer.parseInt(requestPage), Integer.parseInt(pageSize));

        int recordCount = dao.getPageCount1(sbCondition.toString(), new Object[]{});
        int recordSize = Integer.valueOf(pageSize).intValue();

        int pageCount = 0;
        if (recordCount < recordSize) {
            pageCount = 1;
        } else {
            double flag = Math.ceil(recordCount / recordSize);
            pageCount = ((int) flag) + 1;
        }
        if (recordCount == 0) {
            pageCount = 0;
        }
        JSONObject result = new JSONObject();
        JSONObject objSendData = new JSONObject();
        //子对象
        objSendData.put("recordCount", recordCount);
        objSendData.put("pageCount", pageCount);
        objSendData.put("requestPage", 1);
        result.put("pager", objSendData);
        // 子数组对象
        result.put("records", records);
        return result;
    }

    @Override
    public List<JSONObject> getCostSmallNameList() {
        List<JSONObject> jsonObjectList = this.dao.getCostSmallNameList("AND PARENT_ID <> 0", null);
        return jsonObjectList;
    }

    @Override
    public JSONObject getAllAutitPage(String userId, String key, String auditFlag, String type, String createUserName, String pageType, int requestPage, int pageSize, String flag) {
        boolean submitPayer = false;
        StringBuilder condition = new StringBuilder();
        List<Object> sqlArgs = new ArrayList<Object>();
        if (StringUtils.isNotEmpty(key)) {
            condition.append(" AND (TITLE LIKE '%" + key + "%' OR REMARK LIKE '%" + key + "%' OR createUserName LIKE '%" + key + "%') ");
        }
        if (StringUtils.isNotEmpty(auditFlag)) {
            condition.append(" AND auditFlag = ?");
            sqlArgs.add(auditFlag);
        }
        if (StringUtils.isNotEmpty(type)) {
            condition.append(" AND TYPE = ? ");
            sqlArgs.add(type);
        }
        if (StringUtils.isNotEmpty(flag)) {
            condition.append(" AND flag LIKE  '%" + flag + "%'");
            //sqlArgs.add(flag);
        }
        if (StringUtils.isNotEmpty(createUserName)) {
            condition.append(" AND createUserName LIKE  '%" + createUserName + "%'");
        }
        if ("pay".equals(pageType)) {
            List<JSONObject> list = rightOpDao.getJSONListByCondition(" AND E_NAME = ? ", new Object[]{"submitPay"});
            if (list != null && list.size() > 0) {
                String rightOpId = list.get(0).getString("id");
                submitPayer = user2RightOpDao.exist(userId, rightOpId);
            }
            if (submitPayer) {
                condition.append(" AND auditFlag IN ('1','3','4','6') ");
            } else {
                condition.append(" AND auditFlag IN ('3','4','6') ");
            }

        }
        condition.append(" AND (createUserId = ? ");
        condition.append(" OR ( ");
        condition.append(" auditFlag <> '-1' ");
        condition.append(" AND ( ");
        condition.append(" ID IN(SELECT FK_MONEY_ID FROM T_APL_MONEY_AUDIT WHERE AUDITOR_ID = ? AND AUDIT_FLAG <> '-1') ");
        //如果id是谈老板,抄送的不给他显示
        if ("2017121618514C22B68296F31AF8DDE2".equals(userId)) {
            condition.append(" OR ");
            condition.append(" ID IN(SELECT FK_MONEY_ID FROM T_APL_MONEY_COPIER LEFT JOIN T_APL_MONEY_MAIN ON T_APL_MONEY_COPIER.FK_MONEY_ID = T_APL_MONEY_MAIN.ID WHERE T_APL_MONEY_COPIER.COPY_PERSON_ID = ? AND( T_APL_MONEY_MAIN.AUDIT_FLAG = '2' OR T_APL_MONEY_MAIN.AUDIT_FLAG = '4'))");
            //condition.append(" OR ID IN(SELECT FK_BUSINESS_ID FROM T_APL_BUSINESS_COPIER LEFT JOIN T_APL_BUSINESS_MAIN ON T_APL_BUSINESS_COPIER.FK_BUSINESS_ID = T_APL_BUSINESS_MAIN.ID WHERE T_APL_BUSINESS_COPIER.COPY_PERSON_ID = ? AND( T_APL_BUSINESS_MAIN.AUDIT_FLAG = '2'))");暂时去掉商务条件
            //condition.append(" OR ID IN(SELECT FK_EVENT_ID FROM T_TMP_EVENT_COPIER LEFT JOIN T_TMP_EVENT_MAIN ON T_TMP_EVENT_COPIER.FK_EVENT_ID = T_TMP_EVENT_MAIN.ID WHERE T_TMP_EVENT_COPIER.COPY_PERSON_ID = ? AND( T_TMP_EVENT_MAIN.AUDIT_FLAG = '2'))");
            //condition.append(" OR ID IN(SELECT FK_COST_ID FROM t_wrt_cost_copier LEFT JOIN t_wrt_cost ON t_wrt_cost.ID=t_wrt_cost_copier.FK_COST_ID AND( t_wrt_cost.AUDIT_FLAG = '2')");
            sqlArgs.add(userId);
            //sqlArgs.add(userId);
            //sqlArgs.add(userId);
        } else {
            condition.append(" OR ");
            condition.append(" ID IN(SELECT FK_MONEY_ID FROM T_APL_MONEY_COPIER WHERE COPY_PERSON_ID = ?) ");
            //condition.append(" OR ID IN(SELECT FK_BUSINESS_ID FROM T_APL_BUSINESS_COPIER WHERE COPY_PERSON_ID = ?) ");
            condition.append(" OR ID IN(SELECT FK_EVENT_ID FROM T_TMP_EVENT_COPIER WHERE COPY_PERSON_ID = ?) ");
            condition.append(" OR ID IN(SELECT FK_COST_ID FROM t_wrt_cost_copier WHERE COPY_PERSON_ID = ? )");
            sqlArgs.add(userId);
            //sqlArgs.add(userId);
            sqlArgs.add(userId);
            sqlArgs.add(userId);
        }
        condition.append(" OR ");
        condition.append(" ID IN(SELECT FK_MONEY_ID FROM T_APL_MONEY_PAY_AUDIT WHERE AUDITOR_ID = ? AND AUDIT_FLAG <> '1') ");
        condition.append(" OR ID IN(SELECT FK_COST_ID FROM t_wrt_cost_audit WHERE AUDITOR_ID = ? AND AUDIT_FLAG <> '-1')");
        condition.append(" OR ID IN(SELECT MAIN_ID FROM T_APL_BUSINESS_AUDIT WHERE AUDITOR_ID = ? AND AUDIT_FLAG <> '-1') ");
        condition.append(" OR ID IN(SELECT FK_EVENT_ID FROM T_TMP_EVENT_AUDIT WHERE AUDITOR_ID = ? AND AUDIT_FLAG <> '-1') ");
        condition.append(" ) ");
        condition.append(" ) ");
        if ("pay".equals(pageType) && submitPayer) {
            List<JSONObject> listUsers = userDao.getViewJSONListByCondition(" and id = ?", new Object[]{userId});
            List<String> listCompanyIds = new ArrayList<>();
            for (int i = 0; i < listUsers.size(); i++) {
                String userCompanyId = listUsers.get(i).getString("companyId");
                listCompanyIds.add(userCompanyId);
                companyDao.getChildrenIds(userCompanyId, listCompanyIds);
            }
            String companyIds = "";
            for (int i = 0; i < listCompanyIds.size(); i++) {
                companyIds += "'" + listCompanyIds.get(i) + "',";
            }
            companyIds = companyIds.substring(0, companyIds.length() - 1);
            condition.append(" OR companyId IN(" + companyIds + ") ");
        }
        condition.append(" ) ");
        sqlArgs.add(userId);
        sqlArgs.add(userId);
        sqlArgs.add(userId);
        sqlArgs.add(userId);
        sqlArgs.add(userId);
        sqlArgs.add(userId);
        List<JSONObject> prerecords = this.dao.getAllAuditList(userId, condition.toString(), sqlArgs.toArray(), requestPage, pageSize);
        List<JSONObject> records = new ArrayList<JSONObject>();

        for (JSONObject o : prerecords) {
            if ("临时费用".equals(o.getString("flag"))) {
                String money = o.getString("money");
                String predictMoney = o.getString("predictMoney");
                if ("".equals(money) || StringUtils.isBlank(money)) {
                    o.put("money", predictMoney);
                }
                if ("1".equals(o.getString("auditFlag")) && StringUtils.isBlank(o.getString("money")) || "".equals(o.getString("img"))) {
                    o.put("lackFlag", "1");
                } else {
                    o.put("lackFlag", "0");
                }
            }
            records.add(o);
        }
        int recordCount = this.dao.getAllAuditCount(condition.toString(), sqlArgs.toArray());
        int pageCount = recordCount % pageSize == 0 ? recordCount / pageSize : (recordCount / pageSize) + 1;

        JSONObject objPager = new JSONObject();
        objPager.put("recordCount", recordCount);
        objPager.put("pageCount", pageCount);
        //返回
        JSONObject objResult = new JSONObject();
        objResult.put("records", records);
        objResult.put("pager", objPager);
        return objResult;
    }

    @Override
    public JSONObject getLastCost(String userId, String costType, String createTime) {
        return dao.getLastCost(userId, costType, createTime);
    }

}
